<?php

/**
 * File: api.php
 *
 * Interface script for the android app 'english trainee'. It accepts data
 * from the admin app and retrieves some for the game. For running
 * this script please configure 'libs/database.php' with your correct
 * database information.
 *
 * @author     Philipp Petzold <pp@dezign.de>
 * @version    1.0
 */

error_reporting(E_ALL);

// defines
define('INTERFACE_KEY', 'english_trainee_2013');

// import libraries
include_once "libs/database.php";
include_once "libs/english_trainee.php";
include_once "libs/json_writer.php";

// define status codes
$status = array(
	0 => array('status' => array('statuscode' => 'Code: #001', 'code' => 1, 'message' => 'No errors...') ),
	1 => array('status' => array('statuscode' => 'Code: #002', 'code' => 2, 'message' => 'No app id or action was sent...') ),
	2 => array('status' => array('statuscode' => 'Code: #003', 'code' => 3, 'message' => 'App id is invalid...') ),
	3 => array('status' => array('statuscode' => 'Code: #004', 'code' => 4, 'message' => 'Action is invalid...') ),
	4 => array('status' => array('statuscode' => 'Code: #005', 'code' => 5, 'message' => 'Checksum is invalid...') ),
	5 => array('status' => array('statuscode' => 'Code: #006', 'code' => 6, 'message' => 'Game error...') ),
);

// initiate the english trainee
$english_trainee = EnglishTrainee::getInstance();

// initiate the json writer
$json_writer = JSONWriter::getInstance();

// check url params
if(!isset($_GET["cid"]) || !isset($_GET["action"]))
	$json_writer->output($status[1], array());
else if($_GET["cid"] != INTERFACE_KEY)
	$json_writer->output($status[2], array());
else
{
	$english_trainee->createDatabaseStructure();

	if($_GET["action"] == 'create')
	{
		if(!isset($_GET["level"]) || !isset($_GET["word"]) || !isset($_GET["image"]))
			$json_writer->output($status[5], array());

		if(!$english_trainee->insertGameLevel($_GET["level"], $_GET["word"], $_GET["image"]))
			$json_writer->output($status[5], array());
		else
			$json_writer->output($status[0], array());
	}
	else if($_GET["action"] == 'edit')
	{
		if(!isset($_GET["id"]) || !isset($_GET["level"]) || !isset($_GET["word"]) || !isset($_GET["image"]))
			$json_writer->output($status[5], array());

		if(!$english_trainee->updateGameLevel($_GET["id"], $_GET["level"], $_GET["word"], $_GET["image"]))
			$json_writer->output($status[5], array());
		else
			$json_writer->output($status[0], array());
	}
	else if($_GET["action"] == 'retrieve')
	{
		if(!isset($_GET["level"]))
			$json_writer->output($status[5], array());

		$json_writer->output($status[0], $english_trainee->retrieveGameLevel($_GET["level"]));
	}
	else
		$json_writer->output($status[3], array());
}

?>